<template>
  <editor-layout class="tree-edit" @ok="handleOk" v-on="$listeners" v-loading="loading" :loading="saveLoading">
    <el-form size="small" :model="model" :rules="rules" ref="form" @keyup.enter.native="handleOk()" label-width="110px">
      <el-form-item label="上级名称" prop="pid">
        <tree-select
          v-model="model.pid"
          :options="treeData"
          :normalizer="normalizer"
          :show-count="true"
          placeholder="选择上级"
        />
      </el-form-item>
      <el-form-item :label="label" prop="name">
        <el-input type="text" v-model="model.name" clearable />
      </el-form-item>
    </el-form>
  </editor-layout>
</template>
<script>

import treeSelect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: 'tree-edit',
  components: {
    treeSelect
  },
  props: {
    treeData: Array,
    pid: [String, Number],
    name: String,
    id: [String, Number],
    saveFn: Function,
    label: {
      type: String,
      default: '名称'
    }
  },
  data() {
    return {
      loading: false,
      saveLoading: false,
      dataOptions: [],
      model: {
        id: this.id,
        pid: this.pid,
        name: this.name,
      },
      rules: {
        name: [{required: true, message: '必填项'}]
      }
    }
  },
  methods: {
    async init() {
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    handleOk() {
      this.$refs.form.validate(ok => {
        if(!ok) return
        const param = {...this.model}
        if(!param.pid) {
          param.pid = 0
        }

        this.saveLoading = true
        this.saveFn(param).then(res => {
          this.saveLoading = false
          this.$modal.notifySuccess('保存成功!')
          this.$emit('on-ok')
        })
      })
    }
  },
  mounted() {
    this.init()
  }
}
</script>
<style scoped lang="scss">

</style>
